using Assets.Scripts.DL.Enemy.CommonEnemy;
using Assets.Scripts.DL.Enemy.SpriderBoss;
using Assets.Scripts.DL.Enemy.YaSuo;
using Assets.Scripts.DL.Mgrs;
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BossManager : MonoBehaviour
{
    public GameObject BossPrefab;
    public GameObject bossFelledText;
    public Vector3 BossPosition;
    public CinemachineTargetGroup BossTargetGroup;

    public BoxCollider2D Collider1;
    public BoxCollider2D Collider2;
    private GameObject Boss;
    private Controller controller;
    private bool vectory;
    private bool check = false;
    private int count = 0;

    private void Update()
    {
        if (Boss!=null&&
            controller.StateData.IsDie && 
            !check)
        {
            check = true;
            vectory = true;
            StartCoroutine(greatEnemyFailed());
            MusicManager.instance.stopMusic();
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag(Tags.Player)&&!vectory)
        {
            if (count == 0)
            {
                PlayerDataManger.instance.inBossArea = true;
                MusicManager.instance.switchClip(1);
                if (Boss == null)
                {
                    Boss = Instantiate(BossPrefab);
                    Boss.transform.position = BossPosition;
                    BossTargetGroup.m_Targets[1].target = Boss.transform;
                    Collider1.enabled = true;
                    Collider2.enabled = true;
                    controller = Boss.GetComponent<Controller>();
                    if(Boss.GetComponent<SpiderBossController>()!=null)
                        Boss.GetComponent<SpiderBossController>().Player = GameObject.FindGameObjectWithTag(Tags.Player);
                    if (Boss.GetComponent<YasuoController>() != null)
                        Boss.GetComponent<YasuoController>().Player = GameObject.FindGameObjectWithTag(Tags.Player);
                }
                else
                {
                    Boss.SetActive(true);
                }
            }
            count++;
        }
        
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag(Tags.Player))
        {
            count--;
            if (count == 0)
            {
                PlayerDataManger.instance.inBossArea=false;
                MusicManager.instance.switchClip(0);
                if (Boss != null)
                {
                    Destroy(Boss);
                }
            }
        }
    }

    private IEnumerator greatEnemyFailed()
    {
        Collider1.enabled=false;
        Collider2.enabled=false;
        bossFelledText.SetActive(true);
        yield return new WaitForSeconds(3);
        bossFelledText.SetActive(false);
        Destroy(Boss);
    }
}
